package ink.sunflowerk.dao.impl;


import ink.sunflowerk.dao.StudentDao;
import ink.sunflowerk.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Repository//用在持久陈的
@Transactional
public class StudentDaoImp implements StudentDao {

    @Autowired
    SessionFactory sessionFactory;

    public Integer insertStudent(Student student) {
        Session session = sessionFactory.getCurrentSession();
        Serializable save = session.save(student);
        return Integer.valueOf(save.toString());
    }

    public Integer deleteStudentById(Integer sid) {
        String hql = "delete Student where sId =?1";
        int i = sessionFactory.getCurrentSession()
                .createQuery(hql)
                .setParameter(1, sid)
                .executeUpdate();
        return i;

    }

    public int updateStudentById(Student student) {
        // UPDATE `test`.`tab_student` SET `s_birthday` = '2021-12-06 11:39:36' ,`s_dy` = '1'
        // ,`s_name` = 'test6' ,`s_score` = '22' WHERE `s_id` = '14';
        String hql = "update Student set sBirthday=?1 ,sDy=?2,sGender=?3,sName=?4,sScore=?5  where sId=?6";
        Query query = sessionFactory
                .getCurrentSession()
                .createQuery(hql);
        query.setParameter(1, student.getsBirthday());
        query.setParameter(2, student.getsDy());
        query.setParameter(3, student.getsGender());
        query.setParameter(4, student.getsName());
        query.setParameter(5, student.getsScore());
        query.setParameter(6, student.getsId());
        int i = query.executeUpdate();
        return i;
    }

    public Student getOneByKey(Integer sid) {
        return sessionFactory.getCurrentSession().get(Student.class, sid);
    }

    public List<Student> getAll() {
        return (List<Student>) sessionFactory.getCurrentSession().createQuery("from Student ").list();
    }

    public int getCount() {
        Session session = sessionFactory.getCurrentSession();
        String sql = "select count(*) from Student";
        List<Number> list = session.createQuery(sql).list();
        //System.out.println(list);//[2]
        //异常 java.lang.Long cannot be cast to java.lang.Integer
        return Integer.parseInt(list.get(0) + "");
    }

    public List<Student> getPageStudent(int startRow, int rows) {
        Session session = sessionFactory.getCurrentSession();
        String hql = "from Student ";
        Query query = session.createQuery(hql);
        return query.setFirstResult(startRow).setMaxResults(rows).list();
    }
}
